<template>
  <!-- 产量记录 -->
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar :page-no="42" :add-active="addActive" :del-active="delActive" :edit-active="editActive"
        :cancel-active="cancelActive" :save-active="saveActive" :has-edit="false" :has-save="false" :has-cancel="false"
        @add="add" @cancel="cancel('formData')" @edit="edit" @del="del" @save="save('formData')" :hasImportData="true"
        @getNewlistData="getTableDataList" :importApi="'batch/produce/excelImport'"
        :upDownApi="'batch/produce/downloadTemplate'" />
    </template>
    <template v-slot:search-box>
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName === '1'">收起筛选</p>
              <p v-if="activeName === ''">展开筛选</p>
            </div>
          </template>
          <div class="search-btn search-btns" @click.stop="search()">
            <i class="el-icon-circle-check"></i>
            <p>查询</p>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">选择鱼塘</div>
            <el-select filterable clearable v-model="searchList.fishPondId" clearable placeholder="请选择鱼塘" @change="() => {
              $set(searchList, 'productionBatchId', null)
            }">
              <el-option v-for="item in fishPondArr" :key="item.fishPondId" :label="item.pondName"
                :value="item.fishPondId" />
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">批次编号</div>
            <el-select filterable clearable v-model="searchList.productionBatchId" filterable clearable>
              <template v-for="(item, index) in batchListBySearch">
                <el-option v-if="!searchList.fishPondId || item.fishPondId == searchList.fishPondId" :key="index"
                  :label="`${item.mnecode}_${item.varietyName}`" :value="item.productionBatchId" />
              </template>
            </el-select>
          </div>
          <div class="select-box-content select-box-leng-content">
            <div class="select-box-content-name">产出码单号</div>
            <el-input v-model="searchList.codeNumber"></el-input>
          </div>
          <div class="select-box-content select-box-leng-content">
            <div class="select-box-content-name">记录日期</div>
            <el-date-picker v-model="searchList.date" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="yyyy-MM-dd" clearable />
          </div>
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-slot:table-box>
      <el-table v-loading="false" :data="tableData" stripe border height="calc(100% - 50px)" @row-click="handleEdit"
        @selection-change="handleSelectionChange" ref="tableData">
        <el-table-column type="selection" width="55" :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scoped">
            {{ scoped.row.produceId ? scoped.$index + 1 : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="mnecode" min-width="100" label="批次编号" />
        <el-table-column prop="pondName" min-width="100" label="产出鱼塘" />
        <el-table-column prop="fishOutTaskName" min-width="100" label="出鱼任务">
          <template v-if="scope.row.produceId" slot-scope="scope">
            <span :style="{ color: scope.row.fishOutTaskName ? 'blue' : 'green' }"> {{ scope.row.fishOutTaskName ||
              '未使用出鱼任务'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="100" label="产出码单号">
          <template v-if="scope.row.produceId" slot-scope="scope">
            {{ scope.row.codeNumber || '未配置码单号' }}
          </template>
        </el-table-column>
        <el-table-column prop="staffName" min-width="100" label="记录人" />
        <el-table-column prop="varietyName" min-width="100" label="品种" />
        <el-table-column min-width="120" prop="produceDate" label="产出日期" />
        <el-table-column label="详情">
          <template v-if="scope.row.produceId" slot-scope="scope">
            <el-button type="text" class="text-btn-cursor"
              @click="() => { dialogFormVisible = true, isShowFishOutTaskName = false }">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-if="scope.row.produceId" slot-scope="scope">
            <el-button class="text-btn-cursor" type="text" size="small" v-if="judgePermission(42, 'edit')" @click="edit">
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button class="text-btn-cursor cursor-delete" type="text" size="small" v-if="judgePermission(42, 'delete')"
              @click="handleDelete(scope.row)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize"
        @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
    </template>

    <template v-slot:dialog>
      <el-dialog :title="(titleText || '') + '产量信息'" :visible.sync="dialogFormVisible" :before-close="cancel" width="40%">
        <el-form ref="formData" label-position="left" :model="formData" class="el-form" :rules="rules"
          :disabled="nowChanceStau === ''" :show-message="isshowrulemessage">
          <el-form-item label="鱼塘选择:" prop="fishPondId" class="w50p">
            <el-select filterable clearable v-model="formData.fishPondId" filterable clearable placeholder="请选择鱼塘" @change="pondChange"
              :disabled="nowChanceStau !== 'add'">
              <el-option v-for="item in fishPondArr" :key="item.fishPondId" :label="item.pondName"
                :value="item.fishPondId" />
            </el-select>
          </el-form-item>
          <el-form-item label="产出码单号:" prop="codeNumber" class="w50p">
            <el-input v-model="formData.codeNumber"></el-input>
          </el-form-item>
          <el-form-item label="批次编号:" prop="batchList" class="w50p">
            <el-select filterable clearable v-model="formData.batchList" value-key="productionBatchId" clearable filterable placeholder="请选择名称"
              @change="getspecification" :disabled="nowChanceStau !== 'add'">
              <el-option v-for="item in batchList" :key="item.productionBatchId"
                :label="`${item.mnecode}--${item.pondName}--${item.varietyName}`" :value="{
                  productionBatchId: item.productionBatchId,
                  fishVarietyId: item.fishVarietyId,
                  varietyName: item.varietyName,
                  fishPondId: item.fishPondId,
                  weight: item.weight,
                  num: item.num
                }" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="nowChanceStau == 'add'" label="批次详情:" prop="fishOutTaskId" class="w50p">
            <el-input v-model="batchInfo" disabled></el-input>
          </el-form-item>
          <el-form-item v-if="nowChanceStau == 'add'" label="出鱼任务:" prop="fishOutTaskId" class="w50p">
            <el-select filterable clearable v-model="formData.fishOutTaskId" filterable clearable placeholder="可选"
              @change="handleChangeFishOutTask" :disabled="!formData.batchList">
              <el-option v-for="item in taskList" :key="item.fishOutTaskId + 'fishOutTaskId'"
                :label="item.fishOutTaskName" :value="item.fishOutTaskId" />
            </el-select>
          </el-form-item>
          <el-form-item label="记录人:" prop="staffName" class="w50p">
            <el-select filterable clearable disabled v-model="formData.staffName" filterable clearable placeholder="请选择">
              <el-option v-for="item in staffList" :key="item.staffId" :label="item.staffName" :value="item.staffName" />
            </el-select>
          </el-form-item>
          <el-form-item label="产出日期:" prop="produceDate" class="w50p">
            <el-date-picker v-model="formData.produceDate" type="datetime" :disabled="nowChanceStau !== 'add'"
              value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择" :picker-options="pOptions" clearable />
          </el-form-item>
          <el-divider></el-divider>

          <el-form-item v-for="(produceDeta, index) in formData.produceDetailList" :key="index + 'produceDeta'"
            class="w100p">
            <el-form-item label="鱼类类型:" :prop="'produceDetailList.' + index + '.fishType'" :rules="{
              required: true,
              message: '鱼类类型不能为空',
              trigger: 'change',
            }" class="w50p">
              <el-select filterable clearable v-model="produceDeta.fishType" placeholder="选择鱼类类型" filterable clearable>
                <el-option v-for="(item, index) in EnumArr" :key="index" :label="item.value" :value="item.name" />
              </el-select>
            </el-form-item>

            <el-form-item label="产量规格:" :prop="'produceDetailList.' + index + '.specificationId'" class="w50p" :rules="{
              required: true,
              message: '规格不能为空',
              trigger: 'change',
            }">
              <el-select filterable clearable v-model="produceDeta.specificationId" placeholder="选择产量规格" filterable clearable>
                <el-option v-for="(item, index) in specificationList" :key="index" :label="item.specificationName"
                  :value="item.specificationId" />
              </el-select>
            </el-form-item>
            <el-form-item label="产出数量:" :prop="'produceDetailList.' + index + '.num'" class="w50p" :rules="[
              { required: true, message: '数量不能为空', trigger: 'blur' },
              { validator: checkInt, trigger: ['change', 'blur'] }
            ]">
              <el-input v-model="produceDeta.num" placeholder="输入产出数量" type="number" clearable>
                <template slot="append">尾</template>
              </el-input>
            </el-form-item>
            <el-form-item label="产出重量:" :prop="'produceDetailList.' + index + '.weight'" class="w50p" :rules="[
              { required: true, message: '重量不能为空', trigger: 'blur' },
              { validator: checkInt1, trigger: ['change', 'blur'] }
            ]">
              <el-input v-model="produceDeta.weight" placeholder="输入产出产量" type="number" clearable>
                <template slot="append">斤</template>
              </el-input>
            </el-form-item>

            <el-form-item label="产出备注:" :prop="'produceDetailList.' + index + '.remark'" class="w50p">
              <el-input v-model="produceDeta.remark" placeholder="输入产出备注" clearable> </el-input>
            </el-form-item>
            <el-form-item v-if="nowChanceStau !== 'add' && nowChanceStau !== 'edit'" label="产出均重:" class="w50p">
              {{ produceDeta.weight / produceDeta.num || 0 }}斤/尾
            </el-form-item>
            <div class="w100p addE">
              <div class="line-clicks" v-if="(nowChanceStau === 'edit')"
                @click="countList(produceDeta, produceDeta.produceId)">{{ produceDeta.produceId ? '修改' : '添加' }}
              </div>
              <div class="line-clicks"
                v-if="nowChanceStau === 'edit' && formData.produceDetailList.length > 1 && produceDeta.produceId"
                @click="delProduceList(produceDeta, index)">删除
              </div>
              <div class="line-click"
                v-if="(formData.produceDetailList.length > 1 && nowChanceStau === 'add') || (formData.produceDetailList.length > 1 && nowChanceStau === 'edit' && !produceDeta.produceId)"
                @click="delCountList(index)">
                <i class="el-icon-minus"></i>
              </div>
              <div
                v-if="nowChanceStau === 'add' && index === formData.produceDetailList.length - 1 || nowChanceStau === 'edit' && index === formData.produceDetailList.length - 1"
                class="line-click" @click="addCountList()">
                <i class="el-icon-plus"></i>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" v-if="nowChanceStau !== ''" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel('formData')">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import { mymixin } from "@/utils/mixins";
import SearchBox from "@/components/SearchBox";
import { mapGetters } from "vuex";

import outputRecordApi from "@/api/output-manage/output-record";
import outputQueryApi from "@/api/output-manage/output-query";
import FishOutTaskApi from "@/api/output-manage/fish-out-task";
import batchApi from "@/api/batch-mange/index";
import fishPondApi from "@/api/basic-info-manage/fishPond";
import UnitManageApi from "@/api/basic-info-manage/unit-manage";
import staffApi from "@/api/basic-info-manage/staff/index";
import specificationApi from "@/api/basic-info-manage/specification/index";
let maxTime = null
export default {
  name: "outputRecord",
  components: { ActionBar, Pagination, BaseMainSlot, SearchBox },
  mixins: [mymixin],
  data () {
    return {
      pOptions: {
        disabledDate (time) {
          return time.getTime() < new Date(new Date(maxTime).getTime(new Date(maxTime))) || time.getTime() > new Date().getTime();
        },

        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            if (maxTime < date.getTime() - 3600 * 1000 * 24) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            if (maxTime < date.getTime() - 3600 * 1000 * 24 * 7) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }],
      },
      isShowFishOutTaskName: true,
      batchInfo: '',
      isshowrulemessage: false,
      // 下拉选择框相关
      // 出鱼任务列表
      taskList: [],
      // 批次选择列表
      batchListBySearch: [],
      // 批次选择列表
      batchList: [],
      // 产量规格
      specificationList: [],
      // 产量单位
      unitList: [],
      fishPondArr: [],
      // 搜索框对象
      searchList: {},
      rules: {
        batchList: [
          { required: true, message: "请选择批次", trigger: "change" }
        ],
        fishPondId: [
          { required: true, message: "请选择鱼塘", trigger: "change" }
        ],
        staffName: [
          { required: true, message: "请选择产出人", trigger: "change" }
        ],
        produceDate: [
          { required: true, message: "请选择产出日期", trigger: "change" }
        ]
      },
      name: "",
      staffList: [],
      EnumArr: [
        {
          name: "LIVE_FISH",
          value: "活鱼"
        },
        {
          name: "SECONDARY_FISH",
          value: "次鱼"
        }
      ]
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    nowChanceStau (newvalue) {
      maxTime = null
      if (newvalue === "add" || newvalue === "") {
        this.isShowFishOutTaskName = true
        this.$nextTick(() => {
          this.formData = {
            batchList: {},
          };
          this.batchInfo = ''
          let staffName = sessionStorage.getItem("staffName")
          let staffId = sessionStorage.getItem("staffId")
          let userList = this.staffList.filter(item => {
            return Number(item.staffId) === Number(staffId)
          })
          this.formData = {
            staffName: userList.length == 0 ? this.staffList[0].staffName : staffName,
            staffId: userList.length == 0 ? this.staffList[0].staffId : Number(staffId),
          }
          // if (sessionStorage.getItem("staffId") == 1) {
          //   this.formData.staffName = this.staffList[0].staffName
          //   this.formData.staffId = this.staffList[0].staffId
          // } else {
          //   this.formData.staffName = sessionStorage.getItem("staffName")
          //   this.formData.staffId = Number(sessionStorage.getItem("staffId"))
          // }
          this.$set(this.formData, "produceDetailList", [{ key: Date.now() }]);
          this.$refs['formData'] && this.$refs['formData'].resetFields()
          this.$set(this.formData, 'produceDate', new Date())
        })

      } else if (newvalue === 'edit') {
        setTimeout(() => {
          this.getspecification(this.formData)
        }, 100)
      }
      if (newvalue === "") {
        this.isshowrulemessage = false;
      } else {
        this.isshowrulemessage = true;
      }
    }
  },
  created () {
    this.formData = {
      batchList: {}
    };
    maxTime = null
  },
  mounted () {
    this.search();
    this.getselectdatalist();
    this.queryFishOutTask();
    this.queryBatchInfoList()
  },
  methods: {
    handleChangeFishOutTask (id) {
      let chooseItem = [];
      let fishOutObj = {
        fishType: '',
        num: '',
        specificationId: '',
        weight: ''
      };
      this.$set(this.formData, 'produceDetailList', [])
      if (id) {
        chooseItem = this.taskList.filter(item => {
          return item.fishOutTaskId == id
        })
        this.formData.codeNumber = chooseItem[0].codeNumber
        console.log(chooseItem[0].fishOutTaskDetailList)
        // codeNumber
        chooseItem[0].fishOutTaskDetailList.forEach((item, index) => {
          if (this.formData.fishVarietyId == item.fishVarietyId) {
            this.$set(this.formData.produceDetailList, index, {
              fishType: item.fishType,
              num: item.num,
              specificationId: item.specificationId,
              weight: item.weight,
              remark: item.remark
            })
          }
        });
        //去空
        this.formData.produceDetailList = this.formData.produceDetailList.filter(item => { return item })
        if (!this.formData.produceDetailList.length) {
          this.$set(this.formData.produceDetailList, 0, fishOutObj);
          this.$message.info(`该出鱼任务没有${this.formData.varietyName}品种！`);
        } else {
          this.$message.success(`该出鱼任务一共${this.formData.produceDetailList.length}条${this.formData.varietyName}记录！`);
        }
      } else {
        this.$set(this.formData.produceDetailList, 0, fishOutObj);
      }
      setTimeout(() => {
        this.$refs['formData'] && this.$refs['formData'].clearValidate();
      }, 100);
    },
    batchChange (e) {
      maxTime = ''
      this.formData.produceDate = new Date()
      this.batchListBySearch.find(item => {
        if (item.productionBatchId === e) {
          maxTime = new Date(item.buildDateTime)
          // this.formData.produceDate = this.formatDateTimeMHS(maxTime)
          console.log(this.formData.produceDate, maxTime)
          this.formData.batchList = {
            productionBatchId: item.productionBatchId,
            fishVarietyId: item.fishVarietyId,
            varietyName: item.varietyName,
            fishPondId: item.fishPondId,
            weight: item.weight,
            num: item.num
          }
        }
      })
    },
    queryBatchInfoList () {
      batchApi.queryByCondition({ status: "UN_COMPLETE" }).then(res => {
        this.batchList = res.data;
      });
    },
    checkInt (rule, value, callback) {
      if (value) {
        if (Number(value) > 0 && Number(value) % 1 == 0) {
          callback();
        } else {
          return callback(new Error("请输入大于0的正整数"));
        }
      }
    },
    checkInt1 (rule, value, callback) {
      if (value) {
        let y = ''
        if (String(Number(value)).indexOf('.') != -1) {
          let x = String(Number(value)).indexOf('.') + 1;
          y = String(Number(value)).length - x;
        }
        if (Number(value) > 0 && y <= 2) {
          callback();
        } else {
          return callback(new Error("请输入正数(精确至小数点后两位)"));
        }
      }
    },
    queryFishOutTask () {
      FishOutTaskApi.queryTaskList().then(res => {
        this.taskList = res.data
      })
    },
    // 获取当前拥有类型表格
    getTableDataList () {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.searchList
        }
      };
      if (this.searchList?.date) {
        params.entity.produceDateStart = this.searchList.date[0] + ' 00:00:00';
        params.entity.produceDateEnd = this.searchList.date[1] + ' 23:59:59';
      }
      outputRecordApi.queryPageByCondition(params).then(res => {
        this.loading = false;
        if (res.errCode !== undefined) {
          this.$message.error("表格获取失败");
        }
        let data = res.data.content;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        // 赋值数组
        this.tableData = data;
        this.addblankmet();
        this.resetActionBar();
      });
    },
    // 获取下拉框数据 start
    async getselectdatalist () {
      //   // 获取批次
      const { data: batch } = await batchApi.queryByCondition({
      });
      if (batch !== undefined) {
        this.batchListBySearch = batch;
      } else this.batchListBySearch = [];
      // 获取鱼塘
      const { data: resp } = await fishPondApi.queryByCondition({});
      if (resp !== undefined) {
        this.fishPondArr = resp;
      } else this.fishPondArr = [];
      const { data: Unit } = await UnitManageApi.queryByCondition({});
      if (Unit !== undefined) {
        this.unitList = Unit;
      } else this.unitList = [];
      const { data: staff } = await staffApi.queryByCondition({});
      if (staff !== undefined) {
        this.staffList = staff;
      } else this.staffList = [];
    },
    // 根据批次品种查询 规格
    async specification (e) {
      const { data: specification } = await specificationApi.queryByCondition({
        fishVarietyId: e
      });
      if (specification !== undefined) {
        this.specificationList = specification;
      } else this.specificationList = [];
    },

    // 通过品种id查产量规格
    getspecification (e) {
      this.batchChange(e.productionBatchId)
      this.$set(this.formData, "productionBatchId", e.productionBatchId);
      this.$set(this.formData, "fishVarietyId", e.fishVarietyId);
      this.$set(this.formData, "varietyName", e.varietyName);
      this.$set(this.formData, "fishPondId", e.fishPondId);
      this.$set(this.formData, "fishOutTaskId", '');
      this.$set(this.formData.produceDetailList, 0, {});
      let produceDetailList = e.produceDetailList || this.formData.produceDetailList
      if (produceDetailList.length) {
        this.specification(e.fishVarietyId);
        if (e.varietyName) {
          this.batchInfo = `${e.varietyName}约${e.num}尾`;
        } else {
          this.batchInfo = ''
        }
        setTimeout(() => {
          produceDetailList.forEach((item) => { this.$set(item, 'specificationId', undefined) });
        }, 1000);
      }
      // produceDetailList.length > 0 && (this.specification(e.fishVarietyId),
      //   this.batchInfo = `${e.varietyName}约${e.num}尾`,produceDetailList.forEach((item) => { this.$set(item, 'specificationId', undefined) }) // 切换批次，清除对应批次的规格
      //   )
    },
    pondChange (e) {
      this.$set(this.formData, "productionBatchId", undefined);
      this.$set(this.formData, "fishVarietyId", undefined);
      this.$set(this.formData, "varietyName", undefined);
      this.$set(this.formData, "batchList", undefined);
      batchApi.queryByCondition({ fishPondId: e, status: "UN_COMPLETE" }).then(res => {
        this.batchList = res.data
      })
    },
    // 添加一条清单列表
    addCountList () {
      if (this.formData.productionBatchId && this.formData.fishPondId) {
        if (
          this.formData.produceDetailList === undefined ||
          this.formData.produceDetailList === null
        ) {
          this.$set(this.formData, "produceDetailList", []);
        }
        let Obj = {
          productionBatchId: this.formData.productionBatchId,
          fishPondId: this.formData.fishPondId,
          key: Date.now()
        };
        this.formData.produceDetailList.push({ ...Obj });
      } else {
        this.$message.warning("请先选择批次和鱼塘");
      }
    },
    // 删除一条清单列表
    delCountList (index) {
      if (this.formData.produceDetailList.length === 1) {
        return;
      } else {
        this.formData.produceDetailList.splice(index, 1);
      }
    },
    // 获取下拉框数据 ends
    // 表格操作 增删改查 start
    async handleEdit (row) {
      // if (produce !== undefined) {

      this.specification(row.fishVarietyId);
      setTimeout(async () => {
        this.formData = {
          ...row,
          produceDetailList: await this.queryDetail(row.produceId)
        };
        this.$set(this.formData, "batchList", {
          productionBatchId: row.productionBatchId,
          fishVarietyId: row.fishVarietyId,
          produceId: row.produceId,
          fishPondId: row.fishPondIds
        });
        this.addActive = true;
        this.editActive = true;
        this.saveActive = false;
        this.cancelActive = true;
      }, 1000);
    },
    //  查询详情
    async queryDetail (e) {
      const { data: produce } = await outputQueryApi.queryByCondition({
        produceId: e
      });
      if (produce !== undefined) {
        return produce;
      } else return [];
    },
    // 获取批量删除list
    handleSelectionChange (list) {
      this.nowselectedList = [];
      this.nowselectedList = list.map(item => {
        return item.produceId;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    delmessage () {
      if (this.nowChanceStau === "del") {
        outputRecordApi.delListById(this.nowselectedList).then(res => {
          if (res.success) {
            this.search();
            this.$message.success("删除成功");
          } else {
            this.$message.error(res.message);
          }
        });
        this.nowChanceStau = "";
      }
    },
    // 产量详情添加修改
    countList (e, st) {
      if (!st || st === undefined) {
        let addparams = {
          ...e,
          produceId: this.formData.produceId
        };
        delete addparams.batchList;
        outputQueryApi.add(addparams).then(async res => {
          if (res.success) {
            this.$set(
              this.formData,
              "produceDetailList",
              await this.queryDetail(this.formData.produceId)
            );
            this.$message.success("添加成功");
          } else {
            this.$message.error("添加失败");
          }
        });
      } else {
        let editparams = {
          ...e
        };
        outputQueryApi.edit(editparams).then(res => {
          if (res.success) {
            this.$message.success("修改成功");
          } else {
            this.$message.error("修改失败");
          }
        });
      }
    },
    // 弹框内部list 删除
    delProduceList (e, index) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        
      })
        .then(() => {
          outputQueryApi.delById(e.produceDetailId).then(res => {
            if (res.success) {
              this.formData.produceDetailList.splice(index, 1);
              this.resetActionBar()
              this.$message.success("删除成功");
              // this.search();
            } else {
              this.resetActionBar()
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.resetActionBar()
          this.$message("取消删除");
        });
    },
    // 删除
    handleDelete (data) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        
      }).then(() => {
        outputRecordApi.delById({ id: data.produceId }).then(res => {
          if (res.success) {
            this.resetActionBar()
            this.$message.success("删除成功");
            this.search();
          } else {
            this.resetActionBar()
            this.$message.error("删除失败");
          }
        });
      }).catch(() => {
        this.resetActionBar()
        this.$message("取消删除");
      });
    },
    save (formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "add") {
            // this.getvarriety(this.formData.plantVarietyNo)
            let addparams = {
              ...this.formData
            };
            delete addparams.batchList;
            outputRecordApi.add(addparams).then(res => {
              if (res.success) {
                this.search();
                this.$message.success("添加成功");
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.message);
              }
            });
          }
          if (this.nowChanceStau === "edit") {
            let editparams = {
              ...this.formData
            };
            delete editparams.batchList;
            // console.log(this.formData.produceDetailList)
            if (this.formData.produceDetailList.length > 0) {
              this.formData.produceDetailList.forEach(el => {
                !el.direction && this.countList(el)
                this.search();
              });
            } else {
              outputRecordApi.edit(editparams).then(res => {
                if (res.success) {
                  this.search();
                  this.$message.success("修改成功");
                  this.$refs[formData].resetFields();
                } else {
                  this.$message.error("修改失败");
                }
              });
            }
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    }
    // 表格操作 增删改查 end
  }
};
</script>
<style lang="scss" scoped>
.line {
  width: 100%;
  display: flex;
  flex-wrap: nowrap;

  .line-click {
    width: 30px;
    height: 30px;
    background-color: rgb(198, 196, 196);
    display: flex;
    justify-content: center;
    align-items: center;
    border: rgb(214, 214, 214) 1px solid;
    border-radius: 50%;
    margin-bottom: 10px;
    margin-top: 5px;
    margin-left: 5px;
    cursor: pointer;

    .el-icon-minus {
      color: white;
    }
  }
}

.line-click {
  width: 30px;
  height: 30px;
  background-color: rgb(198, 196, 196);
  display: flex;
  justify-content: center;
  align-items: center;
  border: rgb(214, 214, 214) 1px solid;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 20px;
  position: relative;
  right: 0;
  cursor: pointer;

  .el-icon-plus {
    color: white;
  }
}

.line-clicks {
  width: 30px;
  height: 30px;
  // background-color: rgb(198, 196, 196);
  display: flex;
  justify-content: center;
  align-items: center;
  // border: rgb(214, 214, 214) 1px solid;
  color: red;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 20px;
  text-decoration: underline;
  text-underline-position: under;
  position: relative;
  right: 0;
  cursor: pointer;
}

::v-deep .el-form-item {
  .el-form-item {
    margin-bottom: 20px;
  }
}

::v-deep .el-dialog {
  .el-dialog__body {
    max-height: 65vh;
  }
}

.addE {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  // padding: 0 2%;
}

.w50p {
  width: 50%;
}
</style>
